package com.changgou.order.service.impl;

import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.feign.SpuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.goods.pojo.Spu;
import com.changgou.order.pojo.OrderItem;
import com.changgou.order.service.CartService;
import com.changgou.user.feign.UserFeign;
import com.changgou.user.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName CartServiceImpl
 * @Description
 * @Author 洛尘
 * @Date 23:02 2019/11/23
 * @Version 2.1
 **/
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private SkuFeign skuFeign;

    @Autowired(required = false)
    private UserFeign userFeign;

    @Autowired
    private SpuFeign spuFeign;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加购物车
     *
     * @param username 用户名
     * @param skuId    商品详情id
     * @param num      商品数量
     * @return
     */
    @Override
    public void add(String username, Long skuId, Integer num) {
         User user = userFeign.findById(username).getData();
        if ( username !=null ) {
            Sku sku = skuFeign.findById(skuId).getData();
            Spu spu = spuFeign.findById(sku.getSpuId()).getData();
            //商品加入购物车
            OrderItem orderItem = cartAdd(sku, spu, num);
            //商品保存到redis中
            redisTemplate.boundHashOps("cart_" + username).put(skuId, orderItem);
        }
    }

    @Override
    public List<OrderItem> list(String username) {
        List<OrderItem> list = redisTemplate.boundHashOps("cart_"+ username).values();
        return  list;
    }

    //商品加入购物车
    private OrderItem cartAdd(Sku sku, Spu spu, Integer num) {
        OrderItem orderItem = new OrderItem();
        orderItem.setCategoryId1(spu.getCategory1Id());
        orderItem.setCategoryId2(spu.getCategory2Id());
        orderItem.setCategoryId3(spu.getCategory3Id());
        orderItem.setSpuId(spu.getId());
        orderItem.setSkuId(sku.getId());
        orderItem.setName(sku.getName());           // 商品名称
        orderItem.setPrice(sku.getPrice());         // 商品单价
        orderItem.setNum(num);                      // 购买数量
        orderItem.setMoney(sku.getPrice() * num);   // 总金额
        orderItem.setPayMoney(sku.getPrice() * num);// 实付金额 = 总金额 - 优惠券 - e卡等
        orderItem.setImage(sku.getImage());         // 商品图片
        orderItem.setWeight(sku.getWeight());       // 商品重量
        orderItem.setPostFee(9);                    // 商品运费 = 总金额判断是否超过 99   金牌会员
        orderItem.setIsReturn("0");                 // 商品的退货状态
        return orderItem;
    }

}
